#!/usr/bin/python
# coding: utf-8

import urllib
import os
import datetime

urlBase='http://m.weather.com.cn/data/'
cityCodeFile='city_code'

class weatherInfo:
	city=''
	weather=''
	temperature=''
	wind=''
	weather2=''
	temperature2=''
	wind2=''
	weather3=''
	temperature3=''
	wind3=''

def readCityCode(fileName):
	all_content=open(fileName).read()
	city_codes=all_content.split('\n')
	d=dict()
	for city_code in city_codes:
		if(city_code!=''):
			tuple=city_code.split(':')
			if(len(tuple)==2):
				d[tuple[0]]=tuple[1]
	return d

def before6PM():
	s=datetime.datetime.now()
	if s.hour<18:
		return True
	else:
		return False

def getRawWeather(url):
	info=eval(urllib.urlopen(url).read())['weatherinfo']
	result=weatherInfo()
	result.city=info['city']
	result.weather=info['weather1']
	result.temperature=info['temp1']
	result.wind=info['wind1']
	result.weather2=info['weather2']
	result.temperature2=info['temp2']
	result.wind2=info['wind2']
	result.weather3=info['weather3']
	result.temperature3=info['temp3']
	result.wind3=info['wind3']
	return result

def getWeather(cityName):	# cityName is the Chinese name of the city
	cityCodes=readCityCode(cityCodeFile)
	if cityName in cityCodes:
		code=cityCodes[cityName]
		url=urlBase+code+'.html'
		info=getRawWeather(url)
		message=info.city
		if before6PM():
			message+='今天'+info.weather+' '+info.temperature+' '+info.wind
			message+='。明天 '+info.weather2+' '+info.temperature2+' '+info.wind2
			message+='。后天 '+info.weather3+' '+info.temperature3+' '+info.wind3
		else:
			message+='今天夜间到明天白天'+info.weather+' '+info.temperature+' '+info.wind
			message+='。明天夜间到后天白天 '+info.weather2+' '+info.temperature2+' '+info.wind2
		return message
	else:
		return '目前没有'+cityName+'的天气信息'

